{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25f5db45",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import BaggingClassifier\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.model_selection import cross_val_score\n",
    "import matplotlib.pyplot as plt\n",
    "#拆分数据集\n",
    "x,y=load_iris().data,load_iris().target   \n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,\n",
    "random_state=0,test_size=0.5)\n",
    "#k取不同值的情况下，计算模型的预测误差率\n",
    "k_range=range(1,15)\t\t       #设置k值的取值范围\n",
    "k_error=[]\t                                      #k_error用于保存预测误差率数据\n",
    "for k in k_range:\n",
    "    model=KNeighborsClassifier(n_neighbors=k)\n",
    "    scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')\n",
    "\t\t\t       #5折交叉验证\n",
    "    k_error.append(1-scores.mean())\n",
    "#画图，x轴表示k的取值，y轴表示预测误差率\n",
    "plt.rcParams['font.sans-serif']='Simhei'\n",
    "plt.plot(k_range,k_error,'r-')\n",
    "plt.xlabel('k的取值')\n",
    "plt.ylabel('预测误差率')\n",
    "plt.show() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9552d595",
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义模型\n",
    "kNNmodel=KNeighborsClassifier(6)\t\t\t\t\t                                                                           #k近邻模型\n",
    "Baggingmodel=BaggingClassifier(KNeighborsClassifier(6),\n",
    "n_estimators=130,max_samples=0.4,max_features=4,random_state=1)\n",
    "\t\t\t\t\t                      #Bagging模型\n",
    "#训练模型\n",
    "kNNmodel.fit(x_train,y_train)\n",
    "Baggingmodel.fit(x_train,y_train)\n",
    "#评估模型\n",
    "kNN_pre=kNNmodel.predict(x_test)\n",
    "kNN_ac=accuracy_score(y_test,kNN_pre)\n",
    "print(\"k近邻模型预测准确率：\",kNN_ac)\n",
    "Bagging_pre=Baggingmodel.predict(x_test)\n",
    "Bagging_ac=accuracy_score(y_test,Bagging_pre)\n",
    "print(\"基于k近邻算法的Bagging模型的预测准确率：\",Bagging_ac)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "826ce0ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.colors import ListedColormap\n",
    "import numpy as np\n",
    "#拆分数据集\n",
    "x,y=load_iris().data[:,2:4],load_iris().target   \n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y, random_state=0,test_size=50)\n",
    "#训练模型\n",
    "model=RandomForestClassifier(n_estimators=10,random_state=0)\n",
    "model.fit(x_train,y_train)\n",
    "#评估模型\n",
    "pred=model.predict(x_test)\n",
    "ac=accuracy_score(y_test,pred)\n",
    "print(\"随机森林模型的预测准确率：\",ac)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19402231",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
